import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { getInitMenus } from '@/api/userMenus'
import Layout from '@/layout'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    permissionList: [] // 当前用户可以访问的菜单
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PERMISSION_LIST: (state, permissionList) => {
    state.permissionList = permissionList
  }
}

const actions = {
  getCurrenMenuList({ commit }) {
    function buildPermissionList(routes, pList) {
      for (let i = 0; i < pList.length; i++) {
        const p = pList[i]
        if (p.type === 1) { // 菜单
          const route = {
            path: p.path,
            name: p.name
          }
          if (p.redirect) {
            route.redirect = p.redirect
          }
          if (p.meta) {
            route.meta = JSON.parse(p.meta)
          }
          if (p.alwaysShow) {
            route.alwaysShow = p.alwaysShow
          }
          if (p.hidden) {
            route.hidden = p.hidden
          }
          if (p.pid === '0') { // 顶级菜单
            route.component = Layout
          } else {
            //  component: () => import('@/views/dashboard/index'),
            // route.component = () => import(p.component)
            const path = p.component.replace(/^@\/views/, '')
            route.component = ((path) => {
              return (resolve) => {
                // vue2 的全局注册
                // require函数接受变量，必须有一个根目录的常量
                require([`@/views${path}`], resolve)
              }
            })(path)
          }
          if (p.children && p.children.length > 0) {
            route.children = []
            buildPermissionList(route.children, p.children)
          }
          // 为了避免comonent=null 的错误情况出现
          // if (p.component) {
          if (route.component) {
            routes.push(route)
          }
        } else { // type=2 按钮

        }
      }
    }

    return new Promise((resolve, reject) => {
      getInitMenus()
        .then(res => {
          console.log(res)
          if (res.success) {
            // 拿到路由信息 将路由信息赋值给promissionList
            const promissionList = res.data.permissionList
            // 声明规整后的数组
            const routes = []
            // 将路由信息进行规整 - 一般后台返回的数据都需要自行规整
            buildPermissionList(routes, promissionList)
            // 把规整后的数据存入vuex
            commit('SET_PERMISSION_LIST', routes)
            // 添加到路由对象
            resetRouter()
            router.addRoutes(routes)
            resolve()
          } else {
            reject(res)
          }
        })
    })
  },

  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

